// pages/editImg/editImg.js
const app = getApp();
var systemWidth = wx.getSystemInfoSync().screenWidth;
var systemHeight = wx.getSystemInfoSync().screenHeight;
var rpx = parseFloat(systemWidth / 750);
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: "",
    shareTempFilePath: "",
    text: "",
    frameShow: false,
    templateShow: false,
    frameColor: "#ffffff",
    frameList: [
      { "imgUrl": "../../images/photoFrame1.png", color: "#ffffff" },
      { "imgUrl": "../../images/photoFrame2.png", color: "#3a3a3a" },
      { "imgUrl": "../../images/photoFrame3.png", color: "#fd657c" },
      { "imgUrl": "../../images/photoFrame4.png", color: "#6cafff" },
    ],
    mouldList: ["../../images/mould1.jpg",
      // "../../images/mould2.jpg",
      "../../images/mould3.jpg",
      "../../images/mould4.jpg",
    ],
    textFontFamily: "KaiTi",    // 字体
    textColor: "#000000",  // 字体颜色
    mouldShow: true,
    wordType: "color", // 字体或者颜色
    wordFontIndex: "one",
    textColorList: ["#000000", "#df362f", "#333333", "#ffafbb"],
    textSizeList: [
      { "name": "大", "size": "20" },
      { "name": "中", "size": "18" },
      { "name": "小", "size": "15" }
    ],
    colorIndex: 0,
    sizeIndex: 1,
    textSize: "20",
    templateIndex: 0,
    templateList: [
      { "src": "../../images/mould1.jpg", toName: "", fromName: "", toTop: "230", toLeft: "88", fromTop: "500", fromLeft: "320", rotate: "0" },
      // { "src": "../../images/mould2.jpg", toName: "TINA", fromName: "-小詹", toTop: "198", toLeft: "116", fromTop: "412", fromLeft: "306", rotate: "45" },
      { "src": "../../images/mould3.jpg", toName: "", fromName: "", toTop: "224", toLeft: "108", fromTop: "404", fromLeft: "302", rotate: "0" },
      { "src": "../../images/mould4.jpg", toName: "", fromName: "", toTop: "210", toLeft: "110", fromTop: "528", fromLeft: "332", rotate: "0" }
    ],
    screenHeight: "",
    screenWidth: "",
    editType: ""
  },

  // 返回上一步
  goBack: function () {
    wx.navigateBack({
      url: "../index/index"
    })
  },

  // 相框
  showFrame: function () {
    if (this.data.imgUrl == "") {
      app.showError("请先上传照片");
    } else {
      this.setData({
        frameShow: !this.data.frameShow,
        templateShow: false,
      })
    }
  },

  // 改变相框
  changeFrame: function (e) {
    this.setData({
      frameColor: this.data.frameList[e.currentTarget.dataset.index].color
    })
  },

  // 文字的字体和颜色
  chooseWord: function () {
    if (this.data.templateShow) {
      app.showError("此时不能修改字体");
    } else {
      this.setData({
        mouldShow: false
      })
    }
  },

  // 字体和颜色标签切换
  tabCut: function (e) {
    this.setData({
      wordType: e.currentTarget.dataset.type
    })
  },

  // 选择字体
  changeFont: function (e) {
    this.setData({
      wordFontIndex: e.currentTarget.dataset.index,
      textFontFamily: e.currentTarget.dataset.font,
    })
  },

  // 选择字体颜色
  chooseColor: function (e) {
    this.setData({
      colorIndex: e.currentTarget.dataset.index,
      textColor: this.data.textColorList[e.currentTarget.dataset.index]
    })
  },

  // 选择字体大小
  chooseSize: function (e) {
    this.setData({
      sizeIndex: e.currentTarget.dataset.index,
      textSize: this.data.textSizeList[e.currentTarget.dataset.index].size
    })
  },

  // 提交字体
  wordSure: function () {
    this.setData({
      mouldShow: true
    })
  },

  // 模板
  mouldTap: function () {
    this.setData({
      templateShow: !this.data.templateShow,
      frameShow: false,
    })
  },

  // 选择模板
  chooseTemplate: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      templateIndex: index,
      templateSrc: this.data.mouldList[index]
    })
  },

  // 填写名字
  fillToName: function (e) {
    this.data.templateList[this.data.templateIndex].toName = e.detail.value
    this.setData({
      templateList: this.data.templateList,
    })
  },
  fillFormName: function (e) {
    this.data.templateList[this.data.templateIndex].fromName = e.detail.value
    this.setData({
      templateList: this.data.templateList,
    })
  },

  // 还原
  restoretap: function () {
    this.setData({
      frameColor: "#ffffff",
      textColor: "#000000",
      textFontFamily: "KaiTi"
    })
  },

  // 输入文字
  fillText: function (e) {
    this.setData({
      text: e.detail.value
    });
  },

  // 上传图片
  goCutInside: function () {
    wx.navigateTo({
      url: '../cutInside/cutInside',
    })
  },

  // 保存图片
  saveImg: function () {
    if (!this.data.templateShow) {
      if (this.data.imgUrl == "") {
        app.showError("请先上传图片")
      } if (this.data.text.length > 15) {
        app.showError("字数不能超过15个");
      } else {
        this.canvasWrapText(this.data.text, 25 * rpx, 780 * rpx, 315 * rpx, 50 * rpx);
      }
    } else {
      this.canvasDrawMould();
    }
  },

  // canvas画图
  canvasWrapText: function (text, x, y, maxWidth, lineHeight) {
    if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
      return;
    }
    var getTempFilePath = this.getTempFilePath;
    var context = wx.createCanvasContext('myCanvas'); //定义画布
    context.save();
    context.setFillStyle(this.data.frameColor);
    context.fillRect(0, 0, 495 * rpx, 880 * rpx);
    context.drawImage(app.globalData.uploadImgUrl, 25 * rpx, 25 * rpx, 445 * rpx, 705 * rpx); // 图片
    context.drawImage('../../images/qr_code1.jpg', 323 * rpx, 740 * rpx, 147 * rpx, 129 * rpx); // 图片
    // 字符分隔为数组
    var arrText = text.split('');
    var line = '';
    context.font = "normal normal " + this.data.textSize + "px " + this.data.textFontFamily;
    console.log(context.font)
    context.setFillStyle(this.data.textColor);
    for (var n = 0; n < arrText.length; n++) {
      var testLine = line + arrText[n];
      var metrics = context.measureText(testLine);
      var testWidth = metrics.width;
      if (testWidth > maxWidth && n > 0) {
        context.fillText(line, x, y);
        line = arrText[n];
        y += lineHeight;
      } else {
        line = testLine;
      }
    }
    context.fillText(line, x, y);
    context.draw(true, getTempFilePath);
  },

  // canvas画图（模板）
  canvasDrawMould: function () {
    var templateIndex = this.data.templateIndex;
    var src = this.data.templateList[templateIndex].src;
    var toName = this.data.templateList[templateIndex].toName;
    var fromName = this.data.templateList[templateIndex].fromName;
    var toTop = this.data.templateList[templateIndex].toTop;
    var toLeft = this.data.templateList[templateIndex].toLeft;
    var fromTop = this.data.templateList[templateIndex].fromTop;
    var fromLeft = this.data.templateList[templateIndex].fromLeft;
    var rotate = this.data.templateList[templateIndex].rotate;

    var getTempFilePath = this.getTempFilePath;
    var context = wx.createCanvasContext('myCanvas'); //定义画布
    context.save();
    context.drawImage(src, 0, 0, 495 * rpx, 880 * rpx); // 图片

    context.setFontSize(34 * rpx);
    context.setFillStyle("#333333");
    // context.translate(440 * rpx, 247.5 * rpx);
    // context.rotate(5 * Math.PI / 180)
    // context.translate(-440 * rpx, -247.5 * rpx);
    context.fillText(toName, toLeft * rpx, (Number(toTop) + 40) * rpx);
    context.fillText(fromName, fromLeft * rpx, (Number(fromTop) + 60) * rpx);
    context.draw(true, getTempFilePath);
  },

  // 获取临时路径
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: (res) => {
        console.log(res);
        if (res.tempFilePath) {
          this.setData({
            shareTempFilePath: res.tempFilePath
          });
          this.saveImageToPhotosAlbum();
          this.uploadImg(res.tempFilePath);
        }
      },
      fail: res => {
        app.showError(res);
      }
    })
  },

  //保存至相册
  saveImageToPhotosAlbum: function () {
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {

      },
      fail: (err) => {
      }
    })
  },

  // upload上传图片
  uploadImg: function (imgUlr) {
    wx.showLoading({
      mask: true,
      title: '上传中',
    })
    wx.uploadFile({
      url: app.globalData.baseUrl + '/data/updateImg', //仅为示例，非真实的接口地址
      filePath: imgUlr,
      name: 'file',
      formData: {
        "photo": imgUlr
      },
      success: res => {
        console.log(res);
        if (res.data) {
          app.globalData.resultImgUrl = res.data;
          if (this.data.editType == "") {
            wx.navigateBack({
              url: "../launch/launch"
            })
          } else if (this.data.editType == "help") {
            wx.navigateBack({
              url: "../helpSuccess/helpSuccess"
            })
          } else {
            wx.navigateBack({
              url: "../collectSuc/collectSuc"
            })
          }
          wx.hideLoading();
        }
      },
      fail: res => {
        console.log(res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.setData({
      screenHeight: app.globalData.screenHeight,
      screenWidth: app.globalData.screenWidth
    });
    if (e.editType) {
      this.setData({
        editType: e.editType
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    if (app.globalData.uploadImgUrl != "") {
      this.setData({
        imgUrl: app.globalData.uploadImgUrl
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})